//
//  PreviewLocalFileTypeViewController.m
//  MIS Cloud
//
//  Created by goldeney on 13-12-5.
//  Copyright (c) 2013年 goldeneye. All rights reserved.
//

#import "PreviewLocalFileTypeViewController.h"
#import "PreviewLocalFileTypeCell.h"
#import "DateTimeFormat.h"
#import "UIColorDispose.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <AVFoundation/AVFoundation.h>

#import "FileAttributeModel.h"
#import "FilePathHelper.h"

#import <CTAssetsPickerController/CTAssetsPickerController.h>
#import <CTAssetsPickerController/CTAssetsPageViewController.h>
#import <CTAssetsPickerController/CTAssetsPickerController.h>
#import <CTAssetsPickerController/CTAssetsPageViewController.h>
#import <CTAssetsPickerController/CTAssetCollectionViewCell.h>
#import <CTAssetsPickerController/CTAssetsGridView.h>
#import <CTAssetsPickerController/CTAssetsGridViewFooter.h>
#import <CTAssetsPickerController/CTAssetsGridViewCell.h>
#import <CTAssetsPickerController/CTAssetsGridSelectedView.h>
#import <CTAssetsPickerController/CTAssetCheckmark.h>
#import <CTAssetsPickerController/CTAssetSelectionLabel.h>
#import <CTAssetsPickerController/CTAssetsPageView.h>

@interface PreviewLocalFileTypeViewController ()

@property(nonatomic,assign) FileSelectNumberType numberType;
@property(nonatomic,strong) NSMutableDictionary *extension;
@property(nonatomic,strong) NSMutableString *extensionString;

@end

@implementation PreviewLocalFileTypeViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"文件来源";
        self.extension = [[NSMutableDictionary alloc] initWithCapacity:0];
        self.extensionString = [NSMutableString stringWithString:@""];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_tableView registerClass:[PreviewLocalFileTypeCell class] forCellReuseIdentifier:@"PreviewLocalFileTypeCell"];
    _tableView.tableFooterView = [[UIView alloc] init];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setSelectNumberType:(FileSelectNumberType)numberType
{
    self.numberType = numberType;
}

- (void)addExtension:(NSString*)extension
{
    if (!extension) return;
    if (extension.length == 0) return;
    
    if (self.extensionString.length == 0)
    [self.extensionString appendString:extension];
    else [self.extensionString appendFormat:@"、%@",extension];
    
    [self.extension setObject:extension forKey:extension];
}


#pragma mark -
#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 86.0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PreviewLocalFileTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PreviewLocalFileTypeCell"];
    
    //设置页面显示数据
    if (indexPath.row == 0) {
        cell.titleLable.text = @"照片和视频";
        cell.titleLable.textColor = [UIColorDispose colorWithHexString:@"#4498b0"];
        cell.contentLable.text = @"使用相册中的照片和视频";
        cell.iconImageView.image = [UIImage imageNamed:@"file_type_photo.png"];
    } else if (indexPath.row == 1) {
        cell.titleLable.text = @"已下载文件";
        cell.titleLable.textColor = [UIColorDispose colorWithHexString:@"#d5a150"];
        cell.contentLable.text = @"使用已下载的文件";
        cell.iconImageView.image = [UIImage imageNamed:@"file_type_down.png"];
    } else if (indexPath.row == 2) {
        cell.titleLable.text = @"拍照和录像";
        cell.titleLable.textColor = [UIColorDispose colorWithHexString:@"#274361"];
        cell.contentLable.text = @"使用相机生成的照片和视频";
        cell.iconImageView.image = [UIImage imageNamed:@"file_type_ camera.png"];
    }
    
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {//照片和视频
        //设置照片选择样式
        [self setCTApperanceViewControllerStyle];
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // init picker
                CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
                // set delegate
                picker.delegate = self;
                
                // Optionally present picker as a form sheet on iPad
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
                picker.modalPresentationStyle = UIModalPresentationFormSheet;
                
                // present picker
                [self presentViewController:picker animated:YES completion:nil];
            });
        }];
        
    } else if (indexPath.row == 1) {//已下载文件
        PreviewDownFileViewController *addBriefcation = [[PreviewDownFileViewController alloc] init];
        AbstractNavigationController *navigation = [[AbstractNavigationController alloc] initWithRootViewController:addBriefcation];
        addBriefcation.delagate = self;
        
        if (self.numberType == FileSelectNumberTypeOne)
        addBriefcation.selectType = PreviewDownFileSelectTypeOne;
        [self presentViewController:navigation animated:YES completion:nil];
        
    } else if (indexPath.row == 2) {//拍照
        [self addPicEvent];
    }
}

//设置照片选择样式
- (void)setCTApperanceViewControllerStyle
{
    UIColor *color1 = ThemeColorBlue;
    UIColor *color2 = [UIColor whiteColor];
    UIColor *color3 = [UIColor whiteColor];
    UIFont  *font   = [UIFont boldSystemFontOfSize:18];
    
    // Navigation Bar apperance
    UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
    
    // set nav bar style to black to force light content status bar style
    navBar.barStyle = UIBarStyleBlack;
    
    // bar tint color
    navBar.barTintColor = color1;
    
    // tint color
    navBar.tintColor = color2;
    
    // title
    navBar.titleTextAttributes =
    @{NSForegroundColorAttributeName: color2,
      NSFontAttributeName : font};
    
    // bar button item appearance
    UIBarButtonItem *barButtonItem = [UIBarButtonItem appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
    [barButtonItem setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]}
                                 forState:UIControlStateNormal];
    
    // albums view
    UITableView *assetCollectionView = [UITableView appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
    assetCollectionView.backgroundColor = color2;
    
    // asset collection appearance
    //    CTAssetCollectionViewCell *assetCollectionViewCell = [CTAssetCollectionViewCell appearance];
    //    assetCollectionViewCell.titleFont = [font fontWithSize:16.0];
    //    assetCollectionViewCell.titleTextColor = color1;
    //    assetCollectionViewCell.selectedTitleTextColor = color2;
    //    assetCollectionViewCell.countFont = [font fontWithSize:12.0];
    //    assetCollectionViewCell.countTextColor = color1;
    //    assetCollectionViewCell.selectedCountTextColor = color2;
    //    assetCollectionViewCell.accessoryColor = color1;
    //    assetCollectionViewCell.selectedAccessoryColor = color2;
    //    assetCollectionViewCell.backgroundColor = color3;
    //    assetCollectionViewCell.selectedBackgroundColor = [color1 colorWithAlphaComponent:0.4];
    
    // grid view
    CTAssetsGridView *assetsGridView = [CTAssetsGridView appearance];
    assetsGridView.gridBackgroundColor = color3;
    
    // assets grid footer apperance
    CTAssetsGridViewFooter *assetsGridViewFooter = [CTAssetsGridViewFooter appearance];
    assetsGridViewFooter.font = [font fontWithSize:16.0];
    assetsGridViewFooter.textColor = color2;
    
    // grid view cell
    CTAssetsGridViewCell *assetsGridViewCell = [CTAssetsGridViewCell appearance];
    assetsGridViewCell.highlightedColor = [UIColor colorWithWhite:1 alpha:0.3];
    
    // selected grid view
    CTAssetsGridSelectedView *assetsGridSelectedView = [CTAssetsGridSelectedView appearance];
    assetsGridSelectedView.selectedBackgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    assetsGridSelectedView.tintColor = color1;
    assetsGridSelectedView.borderWidth = 3.0;
    
    // check mark
    CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
    checkmark.tintColor = color1;
    [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
    
    // selection label
    CTAssetSelectionLabel *assetSelectionLabel = [CTAssetSelectionLabel appearance];
    assetSelectionLabel.borderWidth = 1.0;
    assetSelectionLabel.borderColor = color3;
    [assetSelectionLabel setSize:CGSizeMake(24.0, 24.0)];
    [assetSelectionLabel setCornerRadius:12.0];
    [assetSelectionLabel setMargin:4.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
    [assetSelectionLabel setTextAttributes:@{NSFontAttributeName : [font fontWithSize:12.0],
                                             NSForegroundColorAttributeName : color3,
                                             NSBackgroundColorAttributeName : color1}];
    
    // page view (preview)
    CTAssetsPageView *assetsPageView = [CTAssetsPageView appearance];
    assetsPageView.pageBackgroundColor = color3;
    assetsPageView.fullscreenBackgroundColor = color2;
    
    // progress view
    [UIProgressView appearanceWhenContainedIn:[CTAssetsPickerController class], nil].tintColor = color1;
}

#pragma marl -
#pragma mark photots & videos

#pragma mark - Navigation Controller Delegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
}


#pragma mark -
#pragma mark - Assets Picker Delegate
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    if (assets.count<=0) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"没有选择文件" delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    if (self.numberType == FileSelectNumberTypeOne && assets.count > 1) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"限制选择一个文件，请删除其他文件" delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    //遍历照片和视频
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    for (PHAsset *dataAsset in assets) {
        if (dataAsset.mediaType == PHAssetMediaTypeImage) {//照片类型
            PHImageManager * imageManager = [PHImageManager defaultManager];
            [imageManager requestImageDataForAsset:dataAsset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                NSURL *url = [info valueForKey:@"PHImageFileURLKey"];
                NSString *str = [url absoluteString];   //url>string
                NSArray *arr = [str componentsSeparatedByString:@"/"];
                NSString *imgName = [arr lastObject];  // 图片名字
                
                UIImage *image = [UIImage imageWithData:imageData];
                CGImageRef ratioThum = image.CGImage;
                
                id valueProperty = [self.extension objectForKey:[imgName pathExtension].lowercaseString];
                if (!valueProperty && self.extension.count > 0) {
                    NSString *message = [NSString stringWithFormat:@"只能上传%@类型文件，请选择相关类型文件",self.extensionString];
                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil
                                                        cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    alert.alertViewStyle=UIAlertViewStyleDefault;
                    [alert show];
                    return;
                }
                
                NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;
                NSArray *arrayImage = [imgName componentsSeparatedByString:@"."];
                
                NSMutableString *fileName = [[NSMutableString alloc] init];
                [fileName appendString:@"【照片】"];
                [fileName appendFormat:@"%ld",(long)interval];
                [fileName appendFormat:@".%@",arrayImage.lastObject];
                
                //获取等比图片
                UIImage* rti = [UIImage imageWithCGImage:ratioThum];
                NSString *pathUrl = [self saveImage:rti withName:fileName];
                
                FileAttributeModel *model = [[FileAttributeModel alloc] init];
                model.absolutePath = pathUrl;
                model.fileName = fileName;
                [dataArray addObject:model];
                
                //关闭窗体
                if(dataArray.count == assets.count){
                    [picker dismissViewControllerAnimated:YES completion:nil];
                    [self popViewControllerAnimated:YES data:dataArray];
                }
            }];
            
        } else if (dataAsset.mediaType == PHAssetMediaTypeVideo) {//视频类型
            PHImageManager * imageManager = [PHImageManager defaultManager];
            [imageManager requestAVAssetForVideo:dataAsset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                AVURLAsset *urlAsset = (AVURLAsset *)asset;
                NSURL *mediaURL = urlAsset.URL;
                
                NSString *str = [mediaURL absoluteString];   //url>string
                NSArray *arr = [str componentsSeparatedByString:@"/"];
                NSString *oldFilename = [arr lastObject];
                
                id valueProperty = [self.extension objectForKey:[oldFilename pathExtension].lowercaseString];
                if (!valueProperty && self.extension.count > 0) {
                    NSString *message = [NSString stringWithFormat:@"只能上传%@类型文件，请选择相关类型文件",self.extensionString];
                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil
                                                        cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    alert.alertViewStyle=UIAlertViewStyleDefault;
                    [alert show];
                    return;
                }
                
                NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;
                NSArray *arrayVoide = [oldFilename componentsSeparatedByString:@"."];
                
                NSMutableString *fileName = [[NSMutableString alloc] init];
                [fileName appendString:@"【视频】"];
                [fileName appendFormat:@"%ld",(long)interval];
                [fileName appendFormat:@".%@",arrayVoide.lastObject];
                
                
                NSString *fullPath = [[FilePathHelper getCachePhotosFolderPath] stringByAppendingPathComponent:fileName];
                fullPath = [fullPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                
                AVAssetExportSession *session = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
                session.outputFileType = AVFileTypeQuickTimeMovie;
                session.outputURL = [NSURL fileURLWithPath:fullPath];
                [session exportAsynchronouslyWithCompletionHandler:^{}];//获取数据并保存
                
                FileAttributeModel *model = [[FileAttributeModel alloc] init];
                model.absolutePath = fullPath;
                model.fileName = fileName;
                [dataArray addObject:model];
                
                //关闭窗体
                if(dataArray.count == assets.count){
                    [picker dismissViewControllerAnimated:YES completion:nil];
                    [self popViewControllerAnimated:YES data:dataArray];
                }
            }];
            
        } else if (dataAsset.mediaType == PHAssetMediaTypeVideo) {//音频
            NSString *message = [NSString stringWithFormat:@"只能上传%@类型文件，请选择相关类型文件",self.extensionString];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil
                                                cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
            return;
            
        } else if (dataAsset.mediaType == PHAssetMediaTypeUnknown) {//未知类型
            NSString *message = [NSString stringWithFormat:@"只能上传%@类型文件，请选择相关类型文件",self.extensionString];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil
                                                cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
            return;
        }
    }
}

- (void)assetsPickerControllerDidCancel:(CTAssetsPickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    // Allow 1 assets to be picked
    if(self.numberType == FileSelectNumberTypeOne)
    return (picker.selectedAssets.count < 1);
    else return (picker.selectedAssets.count < 10);
}


#pragma marl -
#pragma mark Camera View Methods

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

// 判断是否支持某种多媒体类型：拍照，视频
- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0){
        NSLog(@"Media type is empty.");
        return NO;
    }
    NSArray *availableMediaTypes =[UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL*stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
        
    }];
    return result;
}

// 检查摄像头是否支持录像
- (BOOL) doesCameraSupportShootingVideos{
    return [self cameraSupportsMedia:( NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypeCamera];
}

// 检查摄像头是否支持拍照
- (BOOL) doesCameraSupportTakingPhotos{
    return [self cameraSupportsMedia:( NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (void) addPicEvent
{
    // 判断有摄像头，并且支持拍照功能
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]){
        
        // 设置所支持的类型，设置只能拍照，或则只能录像，或者两者都可以
        //NSMutableArray *arrMediaTypes = [NSMutableArray arrayWithCapacity:0];
        id valuePNG = [self.extension objectForKey:@"png"];
        id valueMov = [self.extension objectForKey:@"mov"];
        
        NSArray *arrMediaTypes;
        if(self.extension.count > 0){
            NSString *requiredMediaType = ( NSString *)kUTTypeImage;
            NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
            
            if (valuePNG) arrMediaTypes = [NSArray arrayWithObjects:requiredMediaType,nil];
            if (valueMov) arrMediaTypes = [NSArray arrayWithObjects:requiredMediaType1,nil];
            if (valuePNG && valueMov) arrMediaTypes = [NSArray arrayWithObjects:requiredMediaType, requiredMediaType1,nil];
            
            if (arrMediaTypes.count<=0) {
                NSString *message = [NSString stringWithFormat:@"只能上传%@类型文件，请选择其他选项",self.extensionString];
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil
                                                    cancelButtonTitle:@"确定" otherButtonTitles:nil];
                alert.alertViewStyle=UIAlertViewStyleDefault;
                [alert show];
                return;
            }
            
        } else {
            NSString *requiredMediaType = ( NSString *)kUTTypeImage;
            NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
            arrMediaTypes=[NSArray arrayWithObjects:requiredMediaType, requiredMediaType1,nil];
        }
        
        // 设置所支持的类型，设置只能拍照，或则只能录像，或者两者都可以
        //NSString *requiredMediaType = ( NSString *)kUTTypeImage;
        //NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
        //NSArray *arrMediaTypes=[NSArray arrayWithObjects:requiredMediaType, requiredMediaType1,nil];
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        
        [picker setSourceType:UIImagePickerControllerSourceTypeCamera];// 设置类型
        [picker setMediaTypes:arrMediaTypes];
        [picker setVideoQuality:UIImagePickerControllerQualityTypeMedium];// 设置录制视频的质量
        //[picker setVideoMaximumDuration:10.f];//设置最长摄像时间
        [self presentViewController:picker animated:YES completion:nil];
        
    } else {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"设备不支持该功能" delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
    }
    
}

#pragma mark - 保存图片至沙盒
- (NSString*) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    //对图片大小进行压缩
    CGSize imagesize = currentImage.size;
    imagesize.height =640;
    imagesize.width =480;
    currentImage = [self imageWithImage:currentImage scaledToSize:imagesize];
    
    NSData *imageData = nil;
    if (UIImagePNGRepresentation(currentImage) == nil) {
        imageData = UIImageJPEGRepresentation(currentImage, 1.0);
    } else {
        imageData = UIImagePNGRepresentation(currentImage);
    }
    
    // 获取沙盒目录
    NSString *fullPath = [[FilePathHelper getCachePhotosFolderPath] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    BOOL isSaveSuccess = [imageData writeToFile:fullPath atomically:YES];
    if (isSaveSuccess) {
        NSLog(@"保存照片成功");
    } else {
        NSLog(@"保存照片失败");
    }
    
    return fullPath;
}

//对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}


#pragma mark - 保存视频至沙盒
- (NSString*) saveMovie:(NSData *)currentData withName:(NSString *)fileName
{
    // 获取沙盒目录
    NSString *fullPath = [[FilePathHelper getCachePhotosFolderPath] stringByAppendingPathComponent:fileName];
    // 将图片写入文件
    BOOL isSaveSuccess = [currentData writeToFile:fullPath atomically:YES];
    if (isSaveSuccess) {
        NSMutableArray *dataArray = [[NSMutableArray alloc] init];
        FileAttributeModel *model = [[FileAttributeModel alloc] init];
        model.absolutePath = fullPath;
        model.fileName = fileName;
        [dataArray addObject:model];
        
        NSLog(@"保存视频成功");
        [self popViewControllerAnimated:YES data:dataArray];
    } else {
        NSLog(@"保存视频失败");
    }
    
    return fullPath;
}

#pragma mark –
#pragma mark Camera View Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){// 判断获取类型：图片
        /* 此处info 有六个值
         * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
         * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
         * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
         * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
         * UIImagePickerControllerMediaURL;       // an NSURL
         * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
         * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
         */
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSMutableString *fileName = [[NSMutableString alloc] init];
        [fileName appendString:@"【拍照】"];
        [fileName appendString:[DateTimeFormat getNowTime]];
        [fileName appendString:@".png"];
        NSString *fullPath = [self saveImage:image withName:fileName];
        
        NSMutableArray *dataArray = [[NSMutableArray alloc] init];
        FileAttributeModel *model = [[FileAttributeModel alloc] init];
        model.absolutePath = fullPath;
        model.fileName = fileName;
        [dataArray addObject:model];
        
        NSLog(@"保存照片成功");
        [self popViewControllerAnimated:YES data:dataArray];
        
    } else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){// 判断获取类型：视频
        //获取视频文件的url
        NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSData *movie = [NSData dataWithContentsOfURL:mediaURL];
        NSString *fileName = [NSString stringWithFormat:@"【录像】%@.%@", [DateTimeFormat getNowTime], [mediaURL.absoluteString pathExtension]];
        [self saveMovie:movie withName:fileName];
    }
    
    //关闭页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)popViewControllerAnimated:(BOOL)animated data:(NSMutableArray*)dataArrary
{
    if (self.backResultDelagate) {
        [self.backResultDelagate backResultDataKey:self.key dataValue:dataArrary];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark -
#pragma mark PreviewDownFileDelagate

- (void)didPreviewDownFile:(PreviewDownFileViewController*)viewController data:(NSMutableArray*)dataArrary
{
    for (FileAttributeModel *model in dataArrary) {
        id valueProperty = [self.extension objectForKey:[model.absolutePath pathExtension]];
        if (!valueProperty && self.extension.count > 0) {
            NSString *message = [NSString stringWithFormat:@"只能上传%@类型文件，请选择相关类型文件",self.extensionString];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil
                                                cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
            return;
        }
    }
    
    //关闭页面
    [viewController dismissViewControllerAnimated:YES completion:nil];
    [self popViewControllerAnimated:YES data:dataArrary];
}

@end
